import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Space,
  Button,
  message,
  Modal,
  TreeSelect,
  Checkbox,
  Card,
  Row,
  Col,
  Upload,
  InputNumber,
  Select,
} from 'antd';
import { LoadingOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import UploadUtil from '@/components/UploadUtil';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';

const { confirm } = Modal;
const apiURL = '/api/services/app/SysConfig/';
const apiURLCate = '/api/services/app/Category/';


const ProductEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const [cascaderOption, setCascaderOption] = useState([]);
  const [contentEditor, setContentEditor] = useState('');
  const [fileList, setFileList] = useState([]);
  const [payDestinationOption, setPayDestinationOption] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  const payTypeOptions = [
    { label: intl.formatMessage({ id: 'pages.alipay' }), value: '1' },
    { label: intl.formatMessage({ id: 'pages.wepay' }), value: '2' },
    { label: intl.formatMessage({ id: 'pages.goldcoin' }), value: '3' },
  ];
  useEffect(() => {
    fetchCategory();
    fetchPayDestination();
    if (props.id) {
      getData(props.id);
    }
  }, [props.id]);

  const getData = (id: number) => {
    if (id > 0) {
      request(apiURL + 'GetProductDetail', {
        method: 'Get',
        params: { id },
      }).then((response) => {
        if (response && response.success) {
          const result = response.result;
          result.contents = BraftEditor.createEditorState(result.contents);
          setDatas(result);
          const fileList: any = [];
          if (result.imgUrl) {
            const pics = result.imgUrl.split(',');
            pics.forEach((element: any) => {
              const obj = {
                uid: element,
                name: element,
                response: {
                  result: element,
                },
                status: 'done',
                url: UploadUtil.ossServ + element,
              };
              fileList.push(obj);
            });
          }
          setFileList(fileList);
          result.payType = result.payType ? JSON.parse(result.payType) : [];
          formRef.current.setFieldsValue({ model: result });
        }
      });
    }
  };

  const fetchCategory = () => {
    request(apiURLCate + 'GetTreeDataAsync', {
      method: 'Get',
      params: { layout: 'product' },
    }).then((response) => {
      const resp = response.result;
      setCascaderOption(resp);
    });
  };

  const fetchPayDestination = () => {
    request(apiURL + 'GetPayDestination', {
      method: 'Get',
    }).then((response) => {
      const payDestinationOption = response.result;
      setPayDestinationOption(payDestinationOption);
    });
  };

  const onFinish = async (values: any) => {
    let act = 'InsertProduct';
    let method = 'Post';
    if (values.model.id > 0) {
      act = 'UpdateProduct';
      method = 'Put';
    }
    values.model.contents = contentEditor;
    cascaderOption.forEach((element: any) => {
      if (element.value == values.model.classIndex) {
        values.model.className = element.title;
      }
    });
    if (fileList) {
      const pics: string[] = [];
      fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.imgUrl = pics.toString();
    } else {
      values.model.imgUrl = datas.ImageFileName;
    }

    values.model.payType = JSON.stringify(values.model.payType);

    request(apiURL + act, {
      method,
      data: values.model,
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({id: 'pages.save.success'}));
        props.fetchDatas();
      }
    });
  };

  const ResetForm = () => {
    const data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    request(apiURL + 'Delete', {
      method: 'Delete',
      params: { Id: datas.id },
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({id: 'pages.delete.success'}));
        props.fetchDatas();
        formRef.current.resetFields();
      }
    });
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({id: 'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id: 'pages.delete.confirm'}),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const handleChange = (editorState: any) => {
    setContentEditor(editorState.toHTML());
  };

  const handleUpload = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    setFileList(info.fileList);
  };

  const editorProps = {
    height: 120,
    onChange: handleChange,
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">{intl.formatMessage({ id: 'pages.upload' })}</div>
    </div>
  );

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  const layout2 = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
  };

  return (
    <>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={intl.formatMessage({ id: 'pages.productEdit' })}
          extra={
            <Space>
              <Button type="primary" htmlType="submit" loading={loading} key="1">
                {intl.formatMessage({ id: 'pages.save' })}
              </Button>
              <Button key="2" onClick={ResetForm}>
                {intl.formatMessage({ id: 'pages.reset' })}
              </Button>
              <Button
                key="3"
                danger
                onClick={showConfirm}
                disabled={datas.id == 0 || !datas.id}
              >
                {intl.formatMessage({ id: 'pages.delete' })}
              </Button>
            </Space>
          }
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="id" name={['model', 'id']} hidden>
                <Input />
              </Form.Item>
              <Form.Item label="imageUrl" name={['model', 'imgUrl']} hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name={['model', 'classIndex']}
                label={intl.formatMessage({ id: 'pages.category' })}
                rules={[{ required: true }]}
              >
                <TreeSelect
                  value={datas.classIndex}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={cascaderOption}
                  placeholder={intl.formatMessage({ id: 'pages.selectCategory' })}
                  treeDefaultExpandAll
                />
              </Form.Item>

              <Form.Item
                label={intl.formatMessage({ id: 'pages.title' })}
                name={['model', 'productName']}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.unitPrice' })} required style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item
                    name={['model', 'unitPrice']}
                    rules={[{ required: true }]}
                  >
                    <InputNumber min={0} step={0.01} />
                  </Form.Item>
                  <CateComp layout="ProductIUM" width={200} name={['model', 'ium']} />
                </Input.Group>
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.quantity' })} required style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'quantity']}>
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item name={['model', 'isEnable']} valuePropName="checked">
                    <Checkbox>{intl.formatMessage({ id: 'pages.enable' })}</Checkbox>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.discount' })} name={['model', 'discount']}>
                <InputNumber min={0.05} step={0.01} />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.transactionPurpose' })} name={['model', 'productType']} required>
                <Select style={{ width: 200 }}>
                  {payDestinationOption?.map((item: any) => {
                    return (
                      <Select.Option value={item.value} key={item.value}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.paymentMethod' })} name={['model', 'payType']} required>
                <Checkbox.Group options={payTypeOptions} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={intl.formatMessage({ id: 'pages.minOrderQty' })} name={['model', 'minNum']}>
                <InputNumber min={0} step={0.01} />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.step' })} name={['model', 'step']}>
                <InputNumber min={0} step={0.01} />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.unitDays' })} name={['model', 'days']}>
                <InputNumber />
              </Form.Item>
              <Form.Item name={['model', 'memo']} label={intl.formatMessage({ id: 'pages.memo' })}>
                <Input />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.image' })}>
                <Upload
                  action={UploadUtil.uploadOSS}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: 'Product',
                    objectField: 'ImgUrl',
                  }}
                  listType="picture-card"
                  fileList={fileList}
                  multiple={true}
                  onChange={handleUpload}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item {...layout2} name={['model', 'contents']}>
            <BraftEditor {...editorProps} />
          </Form.Item>
        </Card>
      </Form>
    </>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ProductEdit);
